const { observable, action, runInAction } = require('mobx-miniprogram');
const cloudHelper = require('../../../helpers/cloud_helper');
const dataHelper = require('../../../helpers/data_helper');
const dayjs = require('dayjs');

// 状态描述映射
const STATUS_DESC = {
    1: '草稿',
    2: '已发布',
    3: '生产版本',
    4: '已废弃'
};

// 资料列表Store
const materialListStore = observable({
    // 资料列表
    materials: [],
    
    // 分页
    page: 1,
    size: 10,
    hasMore: true,
    loading: false,
    
    // 筛选条件
    cateId: '',
    searchKey: '',
    statusFilter: null,

    // 设置分类ID
    setCateId: action(function(cateId) {
        this.cateId = cateId;
    }),
    
    // 设置搜索关键词
    setSearchKey: action(function(key) {
        this.searchKey = key;
    }),
    
    // 设置状态筛选
    setStatusFilter: action(function(status) {
        this.statusFilter = status;
    }),
    
    // 搜索资料
    searchMaterials: action(function(key) {
        this.searchKey = key;
        return this.refreshList();
    }),
    
    // 刷新列表
    refreshList: action(async function() {
        runInAction(() => {
            this.page = 1;
            this.hasMore = true;
        });
        return this.fetchMaterials();
    }),
    
    // 加载更多
    loadMore: action(function() {
        if (this.hasMore && !this.loading) {
            runInAction(() => {
                this.page++;
            });
            return this.fetchMaterials();
        }
    }),
    
    // 获取资料列表
    fetchMaterials: action(async function() {
        if (this.loading) return;
        
        runInAction(() => {
            this.loading = true;
        });
        
        try {
            // 构建请求参数
            const params = {
                cateId: this.cateId,
                page: this.page,
                size: this.size
            };
            
            // 添加筛选条件
            if (this.searchKey) {
                params.keyword = this.searchKey;
            }
            
            if (this.statusFilter) {
                params.status = this.statusFilter;
            }
            
            // 调用云函数获取资料列表
            const res = await cloudHelper.callCloudData('material/list', params);
            
            if (!res || !res.data) {
                // 若API未实现，使用模拟数据
                const mockData = this.getMockMaterials();
                
                runInAction(() => {
                    if (this.page === 1) {
                        this.materials = mockData;
                    } else {
                        this.materials = this.materials.concat(mockData);
                    }
                    
                    // 模拟是否还有更多数据
                    this.hasMore = this.page < 3; // 模拟最多3页数据
                    this.loading = false;
                });
                
                return this.materials;
            }
            
            const list = res.data.list || [];
            const total = res.data.total || 0;
            
            // 处理数据
            const materials = list.map(item => {
                return {
                    ...item,
                    statusDesc: STATUS_DESC[item.status] || '未知状态',
                    time: item.createTime ? dayjs(item.createTime).format('YYYY-MM-DD HH:mm') : ''
                };
            });
            
            runInAction(() => {
                if (this.page === 1) {
                    this.materials = materials;
                } else {
                    this.materials = this.materials.concat(materials);
                }
                
                // 判断是否还有更多数据
                this.hasMore = this.materials.length < total;
                this.loading = false;
            });
            
            return materials;
        } catch (err) {
            console.error('获取资料列表失败', err);
            
            // 如果API调用失败，使用模拟数据
            if (this.page === 1) {
                const mockData = this.getMockMaterials();
                runInAction(() => {
                    this.materials = mockData;
                    this.loading = false;
                });
            } else {
                runInAction(() => {
                    this.loading = false;
                });
            }
            
            throw err;
        }
    }),
    
    // 模拟资料数据
    getMockMaterials: function() {
        const materials = [];
        
        for (let i = 0; i < 10; i++) {
            const id = `mock_material_${this.cateId}_${i}`;
            const status = Math.floor(Math.random() * 4) + 1;
            
            materials.push({
                id,
                title: `${this.getCateName(this.cateId)}资料 ${i + 1}`,
                desc: `这是一个${this.getCateName(this.cateId)}资料的示例描述，包含了相关的技术细节和说明。`,
                version: `1.${i}.0`,
                status,
                statusDesc: STATUS_DESC[status],
                time: dayjs().subtract(i, 'day').format('YYYY-MM-DD HH:mm')
            });
        }
        
        return materials;
    },
    
    // 根据分类ID获取分类名称
    getCateName: function(cateId) {
        const cateMap = {
            'pcb': 'PCB',
            'bom': 'BOM',
            'schematic': '原理图',
            'doc': '文档',
            'software': '软件',
            'datasheet': '规格书'
        };
        
        return cateMap[cateId] || '未知';
    }
});

module.exports = {
    materialListStore
}; 